# @file    : create_ppt_test
# @time    : 2025/3/26
# @author  : yongpeng.yao
# @desc    :
import os
import time

from dotenv import load_dotenv

load_dotenv()

import pandas as pd

file_path = 'sales_data.csv'
file_content = pd.read_csv(file_path).to_string(index=False)
print(file_content)

from dashscope import Assistants

assistant = Assistants.create(
    name='我的简单ppt助手',
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    instructions='作为一名数据科学助理，当给定数据和一个查询时，你能编写适当的代码并创建适当的可视化。',
    tools=[{'type': 'code_interpreter'}],
    model='qwen-max'
)

print(assistant)
assistant_id = assistant.id
print('######', 'assistant_id', assistant_id)

from dashscope import Threads

thread = Threads.create(
    messages=[
        {
            'role': 'user',
            'content': f'计算从2022年到2025年每个季度的总销售额，并通过不同的产品将其可视化为折线图，产品线条颜色分别为红，蓝，绿。\n这是我的数据文件内容，请帮我处理：\n{file_content}',
        }
    ],
)
print(thread)
thread_id = thread.id
print('######', 'thread_id', thread_id)

from dashscope import Runs

run = Runs.create(
    assistant_id=assistant_id,
    thread_id=thread_id,
    stream=True,
)
print(run)
for event, msg in run:
    pass

from dashscope import Messages

messages = Messages.list(thread_id=thread_id)
print(messages)


def submit_message_wait_completion(assistant_id_, thread_id_, user_message):
    """
        定义提交用户消息的函数
    :param assistant_id_:
    :param thread_id_:
    :param user_message:
    :return:
    """
    # 检查并等待活跃的Run完成
    for run_ in Runs.list(thread_id=thread_id_).data:
        if run_.status == 'in_progress':
            print(f'等待Run{run_.id}完成......')
            while True:
                run_status = Runs.retrieve(thread_id=thread_id_, run_id=run_.id).status
                if run_status in ('succeeded', 'failed'):
                    break
                time.sleep(5)  # 等待5秒后再次检查状态
    # 提示消息
    params = {
        'thread_id': thread_id_,
        'role': 'user',
        'content': user_message,
    }
    Messages.create(**params)

    # 创建Run
    run_ = Runs.create(assistant_id=assistant_id_, thread_id=thread_id_)
    return run_


def get_response(thread_id_):
    return Messages.list(thread_id=thread_id_)


# 让助手生成见解
run = submit_message_wait_completion(assistant_id, thread_id,
                                     f'请根据你刚才创建的图表{file_content}，给我两个约20字的句子，描述最重要的洞察。这将用于幻灯片展示，揭示出数据背后的“秘密”。')

Runs.wait(run_id=run.id, thread_id=thread_id)

response = get_response(thread_id)
bullet_points = response.data[0].content[0].text.value
print(bullet_points)

# 根据见解生成标题
run = submit_message_wait_completion(assistant_id, thread_id,
                                     f'请根据你刚才创建的情节和要点\n{bullet_points}\n为PPT想一个非常简短的标题，反映你得出的主要见解。')
Runs.wait(run_id=run.id, thread_id=thread_id)

response = get_response(thread_id)
title = response.data[0].content[0].text.value
print(title)
